from .handle import *
from .meta import *
from meta_service.utils import delete_all_files_in_directory

class TopicIndexStore:

    def __init__(self,tis_path:str) -> None:
        self.tis_path = tis_path
        self.tiname = os.path.basename(self.tis_path)
        self.topic_list = []
        self.__clear_all_cache_files()
        mkdir_if_not_exist(self.tis_path)
        self.__get_topics_in_store()
        self.__init_cache_topic()
    
    def __clear_all_cache_files(self):
        self.cache_path = os.path.join(self.tis_path,CACHE_TOPIC_NAME)
        delete_all_files_in_directory(self.cache_path)
    
    def __init_cache_topic(self) -> None:
        self.__ensure_topic_dir_exist(CACHE_TOPIC_NAME)
    
    def __get_topics_in_store(self):
        dirlist = os.listdir(self.tis_path)
        topic_set = set()
        for elem in dirlist:
            path_elem = os.path.join(self.tis_path,elem)
            if os.path.isdir(path_elem):
                topic_set.add(elem)
        self.topic_list = list(topic_set)
    
    def GetTopicList(self):
        return self.topic_list
    
    def __get_topic_path(self,topic_name:str) -> str:
        if self.HasTopic(topic_name):
            return os.path.join(self.tis_path,topic_name)
        raise Exception(f"add topic: {topic_name} first")
    
    def __ensure_topic_dir_exist(self,topic_name:str):
        if self.HasTopic(topic_name) == False:
            self.topic_list.append(topic_name)
        topic_path = self.__get_topic_path(topic_name)
        mkdir_if_not_exist(topic_path)
    
    def HasTopic(self,topic_name:str) -> bool:
        return topic_name in self.topic_list
    
    def GetTopicHandle(self,topic_name:str) -> TopicHandle:
        return self.__build_topic_handle(topic_name)
    
    def EnsureTopicHandle(self,topic_name:str) -> TopicHandle:
        handle = self.__build_topic_handle(topic_name)
        if handle is None:
            self.AddTopic(topic_name)
        return self.__build_topic_handle(topic_name)
    
    def __build_topic_handle(self,topic_name:str) -> TopicHandle:
        if self.HasTopic(topic_name):
            return TopicHandle(
                self.tis_path,
                topic_name
            )
        print(f"do not have topic:{topic_name} in {self.topic_list}")
        return None

    def AddTopic(self,topic_name:str):
        if self.HasTopic(topic_name):
            print(f"topic: {topic_name} already exist")
            return
        self.__ensure_topic_dir_exist(topic_name)
    
    def DelTopic(self,topic_name:str):
        if topic_name in self.topic_list:
            raise Exception("do not support delete topic")
    
